package org.jcc.core.demo;

public class Pattern {

    public static void main(String[] args) {
        int i = 5;
        for (int j = 0; j < i; j++) {
            for (int k = 0; k < i - j - 1; k++) {
                System.out.print("^");
            }
            for (int z = 0; z < 2*j+1; z++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
    
    public void printPattern(int lineCount) {
        String pattern = getPattern(lineCount);
        System.out.print(pattern);
    }

    /**
     * 获取指定行数的图案，比如3行时：
     *   *
     *  ***
     * *****
     *  
     * @param lineCount 指定的行数，1-20之间
     * @return 图案的字符串表示，包括换行符在内
     */
    public String getPattern(int lineCount) {
        if (lineCount < 1) {
            throw new IllegalArgumentException("行数不能小于1!输入值：" + lineCount);
        }
        if (lineCount > 20) {
            throw new IllegalArgumentException("行数不能大于20!输入值：" + lineCount);
        }
        
        StringBuilder pattern = new StringBuilder();
        for (int lineNumber = 0; lineNumber < lineCount; lineNumber++) {
            pattern.append(getLineContent(lineCount, lineNumber));
        }
        return pattern.toString();
    }

    public String getLineContent(int lineCount, int lineNumber) {
        StringBuilder content = new StringBuilder();
        
        String firstPart = getFirstPart(lineCount, lineNumber);
        // 1. 空格部分
        content.append(firstPart);
        // 2. 星号部分
        content.append(getSecondPart(lineNumber));
        // 3. 空格部分
        content.append(firstPart);
        // 4. 换行部分
        content.append(System.lineSeparator());
        
        return content.toString();
    }

    private String getFirstPart(int lineCount, int lineNumber) {
        int count = getElementCountOfFirstPart(lineCount, lineNumber);
        StringBuilder part = new StringBuilder();
        for (int i = 0; i < count; i++) {
            part.append("*");
        }
        return part.toString();
    }

    private String getSecondPart(int lineNumber) {
        int count = getElementCountOfSecondPart(lineNumber);
        StringBuilder part = new StringBuilder();
        for (int i = 0; i < count; i++) {
            part.append(" ");
        }
        return part.toString();
    }
    
    /**
     * 获取每行第一部分的元素个数
     * @param lineCount 总行数
     * @param lineNumber 行号，从0开始
     * @return
     */
    public int getElementCountOfFirstPart(int lineCount, int lineNumber) {
        return lineCount - lineNumber - 1;
    }

    /**
     * 获取每行第二部分的元素个数
     * @param lineNumber 行号，从0开始
     * @return
     */
    public int getElementCountOfSecondPart(int lineNumber) {
        return lineNumber * 2 + 1;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
